package com.ate.lib_core.http.interceptor;

import com.ate.lib_core.http.factory.RetrofitFactory;
import com.ate.lib_core.http.factory.RetrofitType;
import com.blankj.utilcode.util.SPUtils;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Ate
 * @description:
 * @date :2020/12/10 11:19
 */
public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response;
        //验证token
        if (SPUtils.getInstance().contains(Contants.TOKEN_KEY)){
            response = chain.proceed(addToken(request,SPUtils.getInstance().getString(Contants.TOKEN_KEY)));
        }else {
            response = chain.proceed(request);
        }
        if (response.code() == Contants.TOKEN_NON){
            String newToken = createNewToken();
            SPUtils.getInstance().put(Contants.TOKEN_KEY,newToken);
            response = chain.proceed(addToken(request,newToken));
        }
        return response;
    }
    /**
     * 添加token请求头
     */
    private Request addToken(Request request , String token){
        return request.newBuilder().addHeader("Authorization","bearer "+token).build();
    }
    /**
     * 获取新token
     */
    private String createNewToken() throws IOException {
        return Objects.requireNonNull(RetrofitFactory.getInstance().createRetrofit(RetrofitType.NETWORK)
                .getRetrofit().create(TokenApi.class)
                .token("password","411241bc10a1931351c217f10816f1241ba12017a1491121","")
                .execute().body()).access_token;
    }
}
